package com.xyzwps.harbor.service;

import com.xyzwps.harbor.model.User;
import com.xyzwps.harbor.model.UserSession;
import com.xyzwps.harbor.repo.UserSessionRepository;

import static com.xyzwps.harbor.util.HarborException.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class SessionService {

    @Autowired
    private UserSessionRepository userSessionRepository;


    public Mono<String> createSession(User user) {
        // TODO: session 数量控制
        var us = new UserSession();
        us.setUserId(user.getUserId());
        us.setSid(generateSID());
        us.setCreateTime(LocalDateTime.now());
        us.setExpireTime(LocalDateTime.now().plusDays(31));
        return userSessionRepository.save(us).map(UserSession::getSid);
    }

    public Mono<UserSession> getAliveSession(String sid) {
        return userSessionRepository.findBySid(sid)
                .switchIfEmpty(Mono.error(notImplEx("no session found" )))
                .map(session -> {
                    if (session.getExpireTime().isBefore(LocalDateTime.now())) {
                        throw notImplEx("session expired" );
                    }
                    return session;
                });
    }

    private String generateSID() {
        return UUID.randomUUID().toString().replace("-", "" );
    }
}